<?php

/**
 * 获取请求ip
 *
 * @return ip地址
 */
function ip() {
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}

/**
 * 对用户密码进行加密
 * @parame $password
 * @parame $encrypt //加密因子
 * @return string
 */
function password($password,$encrypt='')
{
    $pwd = array();
    $pwd['encrypt'] = $encrypt?$encrypt:random(6, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
    $pwd['password'] = md5(md5($password).$pwd['encrypt']);
    return $encrypt?$pwd['password']:$pwd;
}

/**
 * 产生随机字符串
 *
 * @param    int        $length  输出长度
 * @param    string     $chars   可选的 ，默认为 0123456789
 * @return   string     字符串
 */
function random($length, $chars = '0123456789') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
/**
 * 缩略图
 * @parame $file  文件绝对路径
 * @parame $size //缩略图的宽
 * @return string
 */
function scthumb($file,$size)
{
    /*获取原图宽高*/
    $fileA =  explode("/",$file);
    $basename = $fileA[count($fileA)-1];
    $imageinfo=getimagesize($file);
    $w =  $imageinfo[0];
    $h =  $imageinfo[1];
    if ($w > $h){
        $size = 600;
    }elseif($h > $w){
        $size = 315;
    }
    preg_match("/[^\d]+/",$size,$matchArr);
    $split = $matchArr[0];
    $splits = "";
    if($split)
    {
        $sizeArr = explode($split,$size) ;
        $width = !empty($sizeArr[0])?$sizeArr[0]:"";
        $height=!empty($sizeArr[1])?$sizeArr[1]:0;
        /*如果高度为空 则按照宽度计算同比例高度
        */
        if(!$height)  $height = intval(($width/$w)*$h);
        $splits = $split;
    }else{
        $width =  $size;
        $height = "";
    }
    $targetdir = str_replace($basename,"",$file) ;
    $target = $targetdir."small_".$basename;
    /*如果大于原图宽度直接复制*/
    if($width>=$w || filesize($file)/ 1024 < 400){
        file_put_contents($target,file_get_contents($file));
    }else{
        if(!$height)  $height = intval(($width/$w)*$h);
        $img = Yii::app()->simpleImage->load($file);
        $img->resize($width,$height);
        $img->save($target);
    }
    return $target;
}
/**
 * [将Base64图片转换为本地图片并保存]
 * @TIME   2019-02-28
 * @param  [Base64] $base64_image_content [要保存的Base64]
 * @param  [目录] $path [要保存的路径]
 */
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        $time = time();
        $new_file = $path."/".date('Ym',$time)."/";
        if(!file_exists(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            @mkdir(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file,0777,true);
        }
        $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
        $new_file = $new_file.$time.random(4,$chars).".{$type}";
        if (file_put_contents(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            scthumb(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file,600);
            return $new_file;
        }else{
            return '上传失败';
        }
    }else{
        return '格式不正确';
    }
}

/**
 * [file上传的文件保存保存]
 * @TIME   2019-03-1
 * @param  
 * @param  [目录] $path [要保存的路径]
 */
function file_image_content($img,$path,$reduce=true){
    $time = time();
    $new_file = $path."/".date('Ym',$time)."/";

    if (($img["type"] == "image/gif") || ($img["type"] == "image/jpeg") || ($img["type"] == "image/pjpeg") || ($img["type"] == "image/png") || ($img["type"] == "image/webp")){
        if ($img["error"] > 0){
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";die;
        }
        else{
            //创建文件夹
            if(!file_exists(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                @mkdir(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file,0777,true);
            }
            $type = substr(strrchr($img["name"], '.'), 1);
            $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
            $new_file = $new_file.$time.random(4,$chars).".{$type}";

            $fp=fopen($img["tmp_name"],'rb');
            $image_head = fread($fp,1024);
            fclose($fp);
            if(preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head) && filesize($img["tmp_name"])/ 1024 < 2000){
                if(move_uploaded_file($img["tmp_name"],dirname(dirname(Yii::app()->BasePath)) . '/img/'.$new_file)){
                    return $new_file;
                }else{
                    return '上传失败';
                }
            }else{
                if ($img["type"] == "image/webp"){
                    move_uploaded_file($img["tmp_name"],dirname(dirname(Yii::app()->BasePath)) . '/img/'.$new_file);
                }else{
                    if ($reduce){
                        $Yimg = new Imgcompress($img["tmp_name"]);
                        $Yimg->compressImg(dirname(dirname(Yii::app()->BasePath)) . '/img/'.$new_file);
                    }else{
                        move_uploaded_file($img["tmp_name"],dirname(dirname(Yii::app()->BasePath)) . '/img/'.$new_file);
                    }
                }
                return $new_file;
            }

        }
    }else{
        return '格式错误';
    }
}
function crabImage($imgUrl, $saveDir, $fileName=null){
    $time = time();
    $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
    $saveDir = $saveDir."/".date('Ym',$time)."/";
    if(empty($imgUrl)){
        return false;
    }
    //获取图片信息大小
    $imgSize = getImageSize($imgUrl);
    if(!in_array($imgSize['mime'],array('image/jpg', 'image/gif', 'image/png', 'image/jpeg'),true)){
        return false;
    }

    //获取后缀名
    $_mime = explode('/', $imgSize['mime']);
    $_ext = '.'.end($_mime);

    if(empty($fileName)){  //生成唯一的文件名
        $fileName = $time.random(4,$chars).$_ext;
    }

    //开始攫取
    ob_start();
    readfile($imgUrl);
    $imgInfo = ob_get_contents();
    ob_end_clean();

    if(!file_exists(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir)){
        @mkdir(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir,0777,true);
    }
    $fp = fopen(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir.$fileName, 'a');
    fwrite($fp, $imgInfo);
    fclose($fp);
    if (filesize(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir.$fileName)/ 1024 > 400){
        $w = $imgSize[0];
        $h = $imgSize[1];
        if ($imgSize[0] >1200){
            $w = 1200;
            $h = intval((1200/$imgSize[0])*$imgSize[1]);
        }
        if ($imgSize[1] > 2000){
            $w = intval((2000/$imgSize[1])*$imgSize[0]);
            $h = 2000;
        }
        $img = Yii::app()->simpleImage->load(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir.$fileName);
        $img->resize($w,$h);
        $img->save(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir.$fileName);
    }
    if ($saveDir == "down/pic/".date('Ym',$time)."/"){
        scthumb(dirname(dirname(Yii::app()->BasePath)).'/img/'.$saveDir.$fileName,600);
    }
    return array('file_name'=>$fileName,'save_path'=>$saveDir.$fileName);
}
//转数组 二维
function simplifyData($data){
    foreach($data as $key=>$val){
        $newData[$key] = $val->attributes;
    }
    return $newData;
}

//抓取图片，保存到本地
function contentPicLocal($content,$path){
    $time = time();
    $new_file = $path."/".date('Ym',$time)."/";
    $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
    //创建文件夹
    if(!file_exists(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file)){
        //检查是否有该文件夹，如果没有就创建，并给予最高权限
        @mkdir(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file,0777,true);
    }
    $content = str_replace('data-src', 'data-s', $content);
    preg_match_all('/<(img|IMG).*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.jpeg]))[\'|\"].*?[\/]?>/',$content,$matches);
    $i = 0;
    foreach ($matches[2] as $key => $value) {
        $st = substr($value,0,5);
        if($st == '/img/'){
            $new_file_img = str_replace('/img/', '', $value);
            $newimg = 'https://img.fam365.com/'.$new_file_img;
            $bigimg = str_replace('small_', '', $newimg);
            $imageinfo=getimagesize($bigimg);
            $w =  $imageinfo[0];
            $h =  $imageinfo[1];
            if (strpos($matches[0][$key],'width: 100%; margin: 0px;') !== false){
                $str = '<img src="'.$newimg.'" data-src="'.$bigimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic" style="width: 100%; margin: 0px;">';
            }else if ( strpos($matches[0][$key],'width: 78px; margin: 0px;') !== false){
                $str = '<img src="'.$newimg.'" data-src="'.$bigimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic" style="width: 78px; margin: 0px;">';
            }else{
                $str = '<img src="'.$newimg.'" data-src="'.$bigimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic">';
            }
            $content = str_replace($matches[0][$key],$str,$content);
            $i++;
        }elseif(strpos($value,'https://img.fam365.com/') === false){
            $type = substr(strrchr($value, '.'), 1);
            $new_file_img = $new_file.$time.random(4,$chars).".{$type}";

            $ch = curl_init();
            $fp=fopen(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file_img, 'w');
            curl_setopt($ch, CURLOPT_URL, $value);
            curl_setopt($ch, CURLOPT_FAILONERROR, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 100);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_FILE, $fp); 
            $output = curl_exec($ch);
            $info = curl_getinfo($ch);
            $error = curl_error($ch);
            fclose($fp);

            $size = filesize(dirname(dirname(Yii::app()->BasePath)).'/img/'.$new_file_img);
            if ($size != $info['size_download']) {
                echo "下载失败";
                echo $error;die;
            } else {
                $newimg = 'https://img.fam365.com/'.$new_file_img;
                $imageinfo=getimagesize($newimg);
                $w =  $imageinfo[0];
                $h =  $imageinfo[1];
                if (strpos($matches[0][$key],'width: 100%; margin: 0px;') !== false ){
                    $str = '<img src="'.$newimg.'" data-src="'.$newimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic" style="width: 100%; margin: 0px;">';
                }else if ( strpos($matches[0][$key],'width: 78px; margin: 0px;') !== false){
                    $str = '<img src="'.$newimg.'" data-src="'.$newimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic" style="width: 78px; margin: 0px;">';
                }else{
                    $str = '<img src="'.$newimg.'" data-src="'.$newimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic">';
                }
                $content = str_replace($matches[0][$key],$str,$content);
                $i++;
            }
            curl_close($ch);
        }else{
            $newimg = $value;
            $bigimg = str_replace('small_', '', $newimg);
            $imageinfo=getimagesize($bigimg);
            $w =  $imageinfo[0];
            $h =  $imageinfo[1];
            if (strpos($matches[0][$key],'width: 100%; margin: 0px;') !== false){
                $str = '<img src="'.$newimg.'" data-src="'.$bigimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic" style="width: 100%; margin: 0px;">';
            }else if ( strpos($matches[0][$key],'width: 78px; margin: 0px;') !== false){
                $str = '<img src="'.$newimg.'" data-src="'.$bigimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic" style="width: 78px; margin: 0px;">';
            }else{
                $str = '<img src="'.$newimg.'" data-src="'.$bigimg.'" rel="'.$i.'" data-size="'.$w.'x'.$h.'" class="show-pic">';
            }
            $content = str_replace($matches[0][$key],$str,$content);
            $i++;
        }
    }
    return $content;
}
// 保存关键词
function saveKeyword($keyword,$author)
{
    $res = keywords::model()->findBySql("select * from keywords where keyword = '$keyword'");

    if($res){
        return false;
    }else{
        
        $kd = new keywords;
        $kd->keyword = $keyword;
        $kd->author = $author;
        $kd->save();
        return true;
    }
}

//数组转对象
function arrayToObject($e){
    if( gettype($e)!='array' ) return;
    foreach($e as $k=>$v){
        if( gettype($v)=='array' || getType($v)=='object' )//多维数组
            $e[$k]=(object)arrayToObject($v);
    }
    return (object)$e;
}

//对象转数组
function object_array($array) {  
    if(is_object($array)) {  
        $array = (array)$array;  
    } 
    if(is_array($array)) {
        foreach($array as $key=>$value) {  
            $array[$key] = object_array($value);  
        }  
    }  
    return $array;  
}
//对象转数组2
function object_array_two($array) {
    $modelList = (array)$array;
    $result=array();
    foreach($modelList as $model){
        $result[]=$model->attributes;
    }
    return $result;
}
// 获取点击量
function getClickNum($data,$action,$btype)
{
    return array();
    $ids = '';
    foreach ($data as $key => $value) {
        $ids .= $value['id'].',';
    }
    $ids = rtrim($ids, ",");
    $url = "https://tongji.fam365.com/api/yx_hits_data_api.php?id_str=$ids&action=$action&btype=$btype";
    $res = getCurl($url);
    $res = json_decode($res,true);
    return $res;
}
// 获取点击排序
function getClickPx($type=1,$pid,$classid=0,$classpid=0,$order=30,$page=1)
{
    $url = "https://tongji.fam365.com/api/yx_hits_data_api.php?action=downlist&order=$order&plat=$pid&classid=$classid&classpid=$classpid&page=$page&btype=$type";
    $res = getCurl($url);
    $res = json_decode($res,true);
    return $res;
}
// 百度自动收录
function getBaiDu($ids,$btype)
{
    $key = Yii::app()->params['linkrefer'];
    for ($i = 0;$i <count($key);$i++){
        $urls = '';
        if ($btype == 1){
            $urls[$i] = array($key[$i][1].'/news/'.$ids.'.html',);
        }elseif ($btype == 2){
            $urls[$i] = array($key[$i][1].'/gonglue/'.$ids.'.html',);
        }elseif ($btype == 3){
            $urls[$i] = array($key[$i][1].'/apps/'.$ids.'.html',);
        }elseif ($btype == 4){
            $urls[$i] = array($key[$i][1].'/hj/'.$ids.'.html',);
        }elseif ($btype == 5){
            $urls[$i] = array($key[$i][1].'/ka/'.$ids.'.html',);
        }elseif ($btype == 6){
            $urls[$i] = array(
                $key[$i][1].'/zt/'.$ids.'/index.html',
                $key[$i][1].'/zt/'.$ids.'/news/index.html',
                $key[$i][1].'/zt/'.$ids.'/gl/index.html',
                $key[$i][1].'/zt/'.$ids.'/down/index.html',
                $key[$i][1].'/zt/'.$ids.'/libao/index.html',
            );
        }else{
            $urls[$i] = array($key[$i][1],);
        }
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $key[$i][0],
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls[$i]),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
    }
    return true;
}
// 获取频道点击量
function getClickPdNum($action,$btype)
{
    $url = "https://tongji.fam365.com/api/yx_hits_data_api.php?action=$action&btype=$btype";
    $res = getCurl($url);
    $res = json_decode($res,true);
    return $res;
}
//获取页面信息
function getCurl($url)
{
    $ch = curl_init();
    // 2. 设置选项，包括URL
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_HEADER,0);
    // 3. 执行并获取HTML文档内容
    $output = curl_exec($ch);
    if($output === FALSE ){
        return "CURL Error:".curl_error($ch);
    }
    // 4. 释放curl句柄
    curl_close($ch);
    return $output;
}
//获取页面响应头
function getHeader($url){
    // curl 获取响应头
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // TRUE 将curl_exec()获取的信息以字符串返回，而不是直接输出
    curl_setopt($ch, CURLOPT_HEADER, true); // 返回 response header 默认 false 只会获得响应的正文
    curl_setopt($ch, CURLOPT_NOBODY, true); // 有时候为了节省带宽及时间，只需要响应头
    $response = curl_exec($ch);
    $header = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 获得响应头大小
    curl_close($ch);
    return $header;
}
//文件夹创建
function folder($fileurl){
    $luj =  explode("/",$fileurl);
    array_pop($luj);
    foreach($luj as $pic){
        $str.=$pic."/";
        if(!is_dir("./".$str))  mkdir("./".$str);
    }
}

/**
 * 取得文件扩展
 *
 * @param $filename 文件名
 * @return 扩展名
 */
function fileext($filename) {
    return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

/**
 * 清除缓存
 *
 * @param $filename 文件名
 * @return 扩展名
 */
function clearcache($id,$module,$type) {
    $url = 'https://www.fam365.com/ajax/clearcache/'.$id.'_'.$module.'_'.$type.'.html';
    $res = getCurl($url);
    return $res;
}

/**
 * 图片转base64
 *
 * @param $filename 文件名
 * @return 扩展名
 */
function base64EncodeImage ($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    return $base64_image;
}

//function array_column($input,$column_key,$index_key='')
//{
//    if(!is_array($input)) return;
//    $results=array();
//    if($column_key===null){
//        if(!is_string($index_key)&&!is_int($index_key)) return false;
//        foreach($input as $_v){
//            if(array_key_exists($index_key,$_v)){
//                $results[$_v[$index_key]]=$_v;
//            }
//        }
//        if(empty($results)) $results=$input;
//    }else if(!is_string($column_key)&&!is_int($column_key)){
//        return false;
//    }else{
//        if(!is_string($index_key)&&!is_int($index_key)) return false;
//        if($index_key===''){
//            foreach($input as $_v){
//                if(is_array($_v)&&array_key_exists($column_key,$_v)){
//                    $results[]=$_v[$column_key];
//                }
//            }
//        }else{
//            foreach($input as $_v){
//                if(is_array($_v)&&array_key_exists($column_key,$_v)&&array_key_exists($index_key,$_v)){
//                    $results[$_v[$index_key]]=$_v[$column_key];
//                }
//            }
//        }
//
//    }
//    return $results;
//}

function forbidden($str){
    $forbidden = new CensorHelper();
    $res = $forbidden->check_words($str);
    return $res;
}
/**
 * 查询缓存是否存在
 * 2019 3 13
 */
function IsCache($path,$name,$gtime)
{
    $cachepath = dirname(dirname(Yii::app()->BasePath)).'/admin'.$path.$name.'.json';
    if(file_exists($cachepath)){
        //存在
        $ftime = filemtime($cachepath);
        $time = time();
        if($time - $ftime > $gtime){
            return false;
        }else{
            return true;
        }
    }else{
        return false;
    }
}

/**
 * 存缓存
 * 2019 3 13
 */
function SaveCache($path,$name,$arr)
{
    $cachepath = dirname(dirname(Yii::app()->BasePath)).'/admin'.$path.$name.'.json';
    $jsonarr = json_encode($arr);
    if(file_exists(dirname(dirname(Yii::app()->BasePath)).'/admin'.$path)){
        //存在
        file_put_contents($cachepath,$jsonarr);
    }else{
        mkdir(dirname(dirname(Yii::app()->BasePath)).'/admin'.$path,0777,true);
        file_put_contents($cachepath,$jsonarr);
    }
}

/**
 * 取缓存
 * 2019 3 13
 */
function GetCache($path,$name)
{
    $cachepath = dirname(dirname(Yii::app()->BasePath)).'/admin'.$path.$name.'.json';
    $res = file_get_contents($cachepath);
    return $res;
}

/**
 * 删缓存
 * 2019 3 13
 */
function DelCache($path,$name)
{
    $cachepath = dirname(dirname(Yii::app()->BasePath)).'/admin'.$path.$name.'.json';
    if (!file_exists($cachepath)) return false;
    return unlink($cachepath);
}
?>